﻿using System;
using System.ServiceProcess;
using System.Security.Cryptography.X509Certificates;
using System.Security.Authentication;

namespace org.furia.proxy
{
    partial class Service : ServiceBase
    {
        public Service()
        {
            InitializeComponent();
        }

        #region Windows service specific code
        protected override void OnStart(string[] args)
        {
            DoStart(args);
        }

        protected override void OnStop()
        {
            DoStop();
        }
        #endregion

        private X509Certificate FindCertificate(
            string locationName,
            StoreName storeName,
            string distinguishedName)
        {
            StoreLocation location = (StoreLocation)Enum.Parse(typeof(StoreLocation), locationName);
            X509Store store = new X509Store(storeName, location);
            store.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection collection = store.Certificates.Find(
                X509FindType.FindBySubjectDistinguishedName,
                distinguishedName,
                true);
            X509Certificate2 certificate = collection.Count == 1 ? collection[0] : null;
            store.Close();
            return certificate;
        }

        public void DoStart(string[] args)
        {
            X509Certificate authority;
            X509Certificate certificate;

            authority = FindCertificate(Properties.Settings.Default.StoreLocation, StoreName.Root, Properties.Settings.Default.Authority);

            certificate = FindCertificate(Properties.Settings.Default.StoreLocation, StoreName.My, Properties.Settings.Default.Certificate);

            if (certificate == null || authority == null)
            {
                throw new ArgumentException();
            }

            server.Authority = authority;
            server.Certificate = certificate;
            server.BufferSize = Properties.Settings.Default.BufferSize;
            server.LocalPort = Properties.Settings.Default.LocalPort;
            server.RemotePort = Properties.Settings.Default.RemotePort;
            server.RemoteHost = Properties.Settings.Default.RemoteHost;
            server.Master = Properties.Settings.Default.Master;

            server.Start();
        }

        public void DoStart()
        {
            DoStart(null);
        }

        public void DoStop()
        {
            server.Stop();
        }

    }
}
